from datetime import datetime

from rest_framework.exceptions import ValidationError
from django.utils import timezone
from apps.master.models import CurrencyRateModel, SystemParametersModel
from apps.project.ProjectProcessService import ProjectProcessService
from apps.project.models import ProjectMaintainModel, ProjectQuotaModel, ProjectMaintainAccountModel, \
    ProjectMaintainStageModel, ProjectProcessModel
from decimal import Decimal
from apps.projectbases.models import ProjectPlanHModel
from utils.utils import update_set, update_instance


class MaintainProjectService:
    def __init__(self, request) -> None:
        self.request = request
        super().__init__()


    def initialMaintainProject(self, plan_id:int, quote_id:int):
        quoteQuery = ProjectQuotaModel.objects.filter(id=quote_id, projectPlanFK__id=plan_id).first()
        if quoteQuery is not None:
            # 获取该项目计划书的维护合同的报价单信息
            quote_no = quoteQuery.quote_no  # 报价单号
            quote_date = quoteQuery.quote_date  # 报价日期
            quote_amount = quoteQuery.quote_amount  # 报价金额
            quote_curr = quoteQuery.quote_curr  # 报价币种
            # 获取该项目计划书的信息
            projectPlanQuery = ProjectPlanHModel.objects.get(id=plan_id)
            standard_curr = projectPlanQuery.standard_curr  # 标准币种
            start_date = projectPlanQuery.start_date  # 项目计划书开始日期
            end_date = projectPlanQuery.end_date  # 项目计划书结束日期
            # 根据标准币种与报价币种获取汇率信息
            currQuery = CurrencyRateModel.objects.filter(standard_curr=standard_curr, quote_curr=quote_curr,
                                                         rate_date__gt=start_date, rate_date__lt=end_date).order_by(
                '-rate_date').first()
            if currQuery is not None:
                rate = currQuery.exchange_rate
            else:
                rate = 1

            # 从系统参数表中获取标准单价
            systemQuery = SystemParametersModel.objects.get(param_code='STANDARDPRICE')
            standard_price = systemQuery.param_value
            # 计算维护合同的各种金额、工数
            sales_date = quote_date
            sales_amount = round(quote_amount / rate, 2)  # 预定销售金额
            procurement_obj = round(sales_amount * Decimal('0.2'), 2)  # 采购（管理对象）
            procurement_affect = 0  # 采购（事务手续）
            Maintain_estimates = 0  # 预估维护金额
            quoted_hours = round(sales_amount / Decimal(standard_price), 2)  # 报价工数(人时)
            quoted_days = round(quoted_hours / Decimal('8'), 1)  # 报价工数(人日)
            bugdget_hours = round(quoted_hours * Decimal('0.7'), 2)  # 预算工数(人时)
            reserve_hours = quoted_hours - bugdget_hours  # 预算预备工数(人时)

            data = {
                'sales_date': sales_date,
                'sales_amount': float(sales_amount),
                'procurement_obj': float(procurement_obj),
                'procurement_affect': float(procurement_affect),
                'Maintain_estimates': float(Maintain_estimates),
                'quoted_hours': float(quoted_hours),
                'quoted_days': float(quoted_days),
                'bugdget_hours': float(bugdget_hours),
                'reserve_hours': float(reserve_hours)
            }
            return data
        else:
            return None


    def initMaintainBySalesAmount(self, sales_amount: Decimal):
        """
        后端新建方法用来实现：前端修改预定销售金额时自动计算采购管理对象、报价天数、报价工时、预定工时、预算预备工时
        """
        if sales_amount is not None and sales_amount >= 0:
            # 从系统参数表中获取标准单价
            systemQuery = SystemParametersModel.objects.get(param_code='STANDARDPRICE')
            standard_price = systemQuery.param_value

            procurement_obj = round(sales_amount * Decimal('0.2'), 2)
            quoted_hours = round(sales_amount / Decimal(standard_price), 2)
            quoted_days = round(quoted_hours / Decimal('8'), 1)
            bugdget_hours = round(quoted_hours * Decimal('0.7'), 2)
            reserve_hours = quoted_hours - bugdget_hours

            data = {
                'procurement_obj': float(procurement_obj),
                'quoted_hours': float(quoted_hours),
                'quoted_days': float(quoted_days),
                'bugdget_hours': float(bugdget_hours),
                'reserve_hours': float(reserve_hours)
            }
            return data
        else:
            return None


    def validMaintainProject(self, request):
        projectPlanFK = request.data['projectPlanFK']
        project_name = request.data['project_name']
        quoteFK = request.data['quoteFK']
        order_no = request.data['order_no']
        sales_date = request.data['sales_date']
        sales_amount = request.data.get('sales_amount',0)
        procurement_obj = request.data.get('procurement_obj',0)
        procurement_affect = request.data.get('procurement_affect',0)
        Maintain_estimates = request.data.get('Maintain_estimates',0)
        quoted_days = request.data.get('quoted_days',0)
        quoted_hours = request.data.get('quoted_hours',0)
        bugdget_hours = request.data.get('bugdget_hours',0)
        reserve_hours = request.data.get('reserve_hours',0)

        # 预定销售年月必须处于项目计划书期间内（大于等于开始日、小于等于结束日）
        plan_query = ProjectPlanHModel.objects.get(id=projectPlanFK)
        plan_status = plan_query.project_status
        start_date = plan_query.start_date
        end_date = plan_query.end_date
        # 只有项目计划书处于生效状态，才能进行项目维护
        if plan_status != 'R':
            raise ValidationError("只有生效状态的项目计划书，才能进行项目维护")
        # 预定销售年月必须处于项目计划书维护期间
        if sales_date:
            sales_date = datetime.strptime(sales_date, "%Y-%m-%d").date()
        else:
            if sales_date < start_date or sales_date > end_date:
                raise ValidationError("预定销售年月必须在项目计划书期间内")
        # 预定销售金额不能小于0
        if float(sales_amount) < 0:
            raise ValidationError("预定销售金额必须大于等于0")
        # 采购管理对象不能小于0
        if float(procurement_obj) < 0:
            raise ValidationError("采购管理对象必须大于等于0")
        # 采购管理事务不能小于0
        if float(procurement_affect) < 0:
            raise ValidationError("采购管理事务必须大于等于0")
        # 维护预估金额不能小于0
        if float(Maintain_estimates) < 0:
            raise ValidationError("维护预估金额必须大于等于0")
        # 报价工数（人日）不能小于0
        if float(quoted_days) < 0:
            raise ValidationError("报价工数（人日）必须大于等于0")
        # 报价工数（人时）不能小于0
        if float(quoted_hours) < 0:
            raise ValidationError("报价工数（人时）必须大于等于0")
        # 预算工数（人时）不能小于0
        if float(bugdget_hours) < 0:
            raise ValidationError("预算工数（人时）必须大于等于0")
        # 预算预备工数（人时）不能小于0
        if float(reserve_hours) < 0:
            raise ValidationError("预算预备工数（人时）必须大于等于0")
        # 未来可能会利用接口或其他方法来判断order_no是否在manpower中存在
        # 。。。


    # def createMaintainProjectRequest(self, request):
    #     # maintain_list = ProjectMaintainModel() # 创建维护项目模型实例（此时其中的数据是创建model时的默认值），主要用于赋值，然后调用save方法保存到数据库
    #     # self.validMaintainProject(request)  # 通用数据校验
    #
    #     projectPlanFK       = request.data['projectPlanFK']
    #     project_name        = request.data['project_name']
    #     quoteFK             = request.data['quoteFK']
    #     order_no            = request.data['order_no']
    #     sales_date          = request.data.get('sales_date',None)
    #     sales_amount        = request.data.get('sales_amount',0)
    #     procurement_obj     = request.data.get('procurement_obj',0)
    #     procurement_affect  = request.data.get('procurement_affect',0)
    #     Maintain_estimates  = request.data.get('Maintain_estimates',0)
    #     quoted_days         = request.data.get('quoted_days',0)
    #     quoted_hours        = request.data.get('quoted_hours',0)
    #     bugdget_hours       = request.data.get('bugdget_hours',0)
    #     reserve_hours       = request.data.get('reserve_hours',0)
    #     note                = request.data.get('note', None) # 使用get方法，若没有获取到数据则返回默认值
    #
    #     # 在新建时：项目计划书+报价单号+订单号必须是唯一的
    #     if ProjectMaintainModel.objects.filter(projectPlanFK__exact=projectPlanFK, quoteFK__exact=quoteFK, order_no=order_no).exists():
    #         raise ValidationError("项目计划书+报价单+订单号必须是唯一的")
    #     planInstance = ProjectPlanHModel.objects.get(id=projectPlanFK) # 获取项目计划书实例
    #     quoteInstance = ProjectQuotaModel.objects.get(id=quoteFK) # 获取报价单实例
    #     # 更新维护项目表
    #     maintain_data = {
    #         'projectPlanFK': planInstance,
    #         'project_name': project_name,
    #         'project_status': 'O',
    #         'quoteFK': quoteInstance,
    #         'order_no': order_no,
    #         'sales_date': sales_date,
    #         'sales_amount': sales_amount,
    #         'procurement_obj': procurement_obj,
    #         'procurement_affect': procurement_affect,
    #         'Maintain_estimates': Maintain_estimates,
    #         'quoted_days': quoted_days,
    #         'quoted_hours': quoted_hours,
    #         'bugdget_hours': bugdget_hours,
    #         'reserve_hours': reserve_hours,
    #         'note': note
    #     }
    #     maintain_project = ProjectMaintainModel.objects.create(**maintain_data, **update_set(request, True))
    #
    #     sales_date_monthly = timezone.now().date().replace(month=1, day=1) # 获取当前年份的一月一号作为起始日期
    #     monthly_sales_amount = round(float(sales_amount) / 12,2) # 每个月的“预定销售金额”
    #     monthly_quoted_hours = round(float(quoted_hours) / 12,2) # 每个月的“报价工数”
    #     monthly_reserve_hours = round(float(reserve_hours) / 12,2) # 每个月的“预算工数”
    #     account_instances = [] # 项目核算履历数组
    #     stage_instances = [] # 阶段别预实数组
    #     for i in range(12):
    #         # 获取当前年份的每个月的一号
    #         current_date = sales_date_monthly.replace(month=(sales_date_monthly.month + i - 1) % 12 + 1,
    #                                           year=sales_date_monthly.year + ((sales_date_monthly.month + i - 1) // 12))
    #         # 项目核算履历数据
    #         account_data = {
    #             'projectMaintainFK': maintain_project,
    #             'sales_date': current_date,
    #             'sales_amount': monthly_sales_amount,
    #             'amount': float(0),
    #             'profit_loss': monthly_sales_amount
    #         }
    #         # 阶段别预实数据
    #         stage_data = {
    #             'projectMaintainFK': maintain_project,
    #             'sales_date': current_date,
    #             'quoted_hours': monthly_quoted_hours,
    #             'bugdget_hours': monthly_reserve_hours,
    #             'actual_hours':float(0),
    #             'margin_hours': bugdget_hours
    #         }
    #
    #         account_instance = ProjectMaintainAccountModel(**account_data, **update_set(request, True))
    #         account_instances.append(account_instance)
    #
    #         stage_instance = ProjectMaintainStageModel(**stage_data, **update_set(request, True))
    #         stage_instances.append(stage_instance)
    #
    #     ProjectMaintainAccountModel.objects.bulk_create(account_instances) # 更新项目核算履历表:维护项目自动拆分成12个月
    #     ProjectMaintainStageModel.objects.bulk_create(stage_instances) # 更新阶段别预实管理表:维护项目自动拆分成12个月
    #
    #     # 插入进度记录
    #     processService = ProjectProcessService(request)
    #     processService.createProjectProcess('O', maintain_project)
    #
    #     return maintain_project

    def createMaintainProjectRequest(self, request):
        projectPlanFK       = request.get('projectPlanFK')
        project_name        = request.get('project_name')
        quoteFK             = request.get('quoteFK')
        order_no            = request.get('order_no')
        sales_date          = request.get('sales_date',None)
        sales_amount        = request.get('sales_amount',0)
        procurement_obj     = request.get('procurement_obj',0)
        procurement_affect  = request.get('procurement_affect',0)
        Maintain_estimates  = request.get('Maintain_estimates',0)
        quoted_days         = request.get('quoted_days',0)
        quoted_hours        = request.get('quoted_hours',0)
        bugdget_hours       = request.get('bugdget_hours',0)
        reserve_hours       = request.get('reserve_hours',0)
        note                = request.get('note', None) # 使用get方法，若没有获取到数据则返回默认值
        user                = self.request.user
        now                 = datetime.now()
        path                = self.request.path_info
        method              = self.request.method
        # 在新建时：项目计划书+报价单号+订单号必须是唯一的
        if ProjectMaintainModel.objects.filter(projectPlanFK__exact=projectPlanFK, quoteFK__exact=quoteFK, order_no=order_no).exists():
            raise ValidationError("项目计划书+报价单+订单号必须是唯一的")
        # 更新维护项目表
        maintain_data = {
            'projectPlanFK': projectPlanFK,
            'project_name': project_name,
            'project_status': 'O',
            'quoteFK': quoteFK,
            'order_no': order_no,
            'sales_date': sales_date,
            'sales_amount': sales_amount,
            'procurement_obj': procurement_obj,
            'procurement_affect': procurement_affect,
            'Maintain_estimates': Maintain_estimates,
            'quoted_days': quoted_days,
            'quoted_hours': quoted_hours,
            'bugdget_hours': bugdget_hours,
            'reserve_hours': reserve_hours,
            'note': note,
            'created':user,
            'created_date': now,
            'created_program': method + ' -> ' + path,
            'updated': user,
            'updated_date': now,
            'updated_program': method + ' -> ' + path
        }
        maintain_project = ProjectMaintainModel.objects.create(**maintain_data)

        sales_date_monthly = timezone.now().date().replace(month=1, day=1) # 获取当前年份的一月一号作为起始日期
        monthly_sales_amount = round(sales_amount / 12,2) # 每个月的“预定销售金额”
        monthly_quoted_hours = round(quoted_hours / 12,2) # 每个月的“报价工数”
        monthly_reserve_hours = round(reserve_hours / 12,2) # 每个月的“预算工数”
        account_instances = [] # 项目核算履历数组
        stage_instances = [] # 阶段别预实数组
        for i in range(12):
            # 获取当前年份的每个月的一号
            current_date = sales_date_monthly.replace(month=(sales_date_monthly.month + i - 1) % 12 + 1,
                                              year=sales_date_monthly.year + ((sales_date_monthly.month + i - 1) // 12))
            # 项目核算履历数据
            account_data = {
                'projectMaintainFK': maintain_project,
                'sales_date': current_date,
                'sales_amount': monthly_sales_amount,
                'amount': Decimal(0),
                'profit_loss': monthly_sales_amount,
                'created': user,
                'created_date': now,
                'created_program': method + ' -> ' + path,
                'updated': user,
                'updated_date': now,
                'updated_program': method + ' -> ' + path
            }
            # 阶段别预实数据
            stage_data = {
                'projectMaintainFK': maintain_project,
                'sales_date': current_date,
                'quoted_hours': monthly_quoted_hours,
                'bugdget_hours': monthly_reserve_hours,
                'actual_hours':Decimal(0),
                'margin_hours': bugdget_hours,
                'created': user,
                'created_date': now,
                'created_program': method + ' -> ' + path,
                'updated': user,
                'updated_date': now,
                'updated_program': method + ' -> ' + path
            }

            account_instance = ProjectMaintainAccountModel(**account_data)
            account_instances.append(account_instance)

            stage_instance = ProjectMaintainStageModel(**stage_data)
            stage_instances.append(stage_instance)

        ProjectMaintainAccountModel.objects.bulk_create(account_instances) # 更新项目核算履历表:维护项目自动拆分成12个月
        ProjectMaintainStageModel.objects.bulk_create(stage_instances) # 更新阶段别预实管理表:维护项目自动拆分成12个月

        # 插入进度记录
        processService = ProjectProcessService(request)
        processService.createProjectProcess('O', maintain_project)

        return maintain_project

    def updateMaintainProjectRequest(self, maintain_list:ProjectMaintainModel, request):
        maintain_id         = self.request.data['id']
        projectPlanFK       = request.get('projectPlanFK')
        project_name        = request.get('project_name')
        quoteFK             = request.get('quoteFK')
        project_status      = request.get('project_status')
        order_no            = request.get('order_no')
        sales_date          = request.get('sales_date', None)
        sales_amount        = request.get('sales_amount', 0)
        procurement_obj     = request.get('procurement_obj', 0)
        procurement_affect  = request.get('procurement_affect', 0)
        Maintain_estimates  = request.get('Maintain_estimates', 0)
        quoted_days         = request.get('quoted_days', 0)
        quoted_hours        = request.get('quoted_hours', 0)
        bugdget_hours       = request.get('bugdget_hours', 0)
        reserve_hours       = request.get('reserve_hours', 0)
        note                = request.get('note', None)
        user                = self.request.user
        now                 = datetime.now()
        path                = self.request.path_info
        method              = self.request.method

        if project_status != 'O':
            raise ValidationError("只有初始状态的项目才可以被更新")

        # 更新维护项目表
        maintain_list.projectPlanFK = projectPlanFK
        maintain_list.project_name = project_name
        maintain_list.project_status = project_status
        maintain_list.quoteFK = quoteFK
        maintain_list.order_no = order_no
        maintain_list.sales_date = sales_date
        maintain_list.sales_amount = sales_amount
        maintain_list.procurement_obj = procurement_obj
        maintain_list.procurement_affect = procurement_affect
        maintain_list.Maintain_estimates = Maintain_estimates
        maintain_list.quoted_days = quoted_days
        maintain_list.quoted_hours = quoted_hours
        maintain_list.bugdget_hours = bugdget_hours
        maintain_list.reserve_hours = reserve_hours
        maintain_list.note = note
        maintain_list.updated = user
        maintain_list.updated_date = now
        maintain_list.updated_program = method + ' -> ' + path
        maintain_list.save()

        monthly_sales_amount = round(sales_amount / 12, 2)  # 每个月的“预定销售金额”
        monthly_quoted_hours = round(quoted_hours / 12, 2)  # 每个月的“报价工数”
        monthly_reserve_hours = round(reserve_hours / 12, 2)  # 每个月的“预算工数”
        account_query = ProjectMaintainAccountModel.objects.filter(projectMaintainFK=maintain_id)
        for account in account_query:
            # 更新项目核算履历表
            account.sales_amount = monthly_sales_amount
            account.profit_loss = monthly_sales_amount
            account.updated = user
            account.updated_date = now
            account.updated_program = method + ' -> ' + path
            account.save()

        # 更新阶段别预实管理表
        stage_query = ProjectMaintainStageModel.objects.filter(projectMaintainFK=maintain_id)
        for stage in stage_query:
            stage.quoted_hours = monthly_quoted_hours
            stage.bugdget_hours = monthly_reserve_hours
            stage.margin_hours = monthly_reserve_hours
            stage.updated = user
            stage.updated_date = now
            stage.updated_program = method + ' -> ' + path
            stage.save()

        return maintain_list


    # def updateMaintainProjectRequest(self, maintain_list:ProjectMaintainModel, request):
    #     maintain_id = request.data['id']
    #     projectPlanFK = request.data['projectPlanFK']
    #     project_name = request.data['project_name']
    #     quoteFK = request.data['quoteFK']
    #     project_status = request.data['project_status']
    #     order_no = request.data['order_no']
    #     sales_date = request.data.get('sales_date', None)
    #     sales_amount = request.data.get('sales_amount', 0)
    #     procurement_obj = request.data.get('procurement_obj', 0)
    #     procurement_affect = request.data.get('procurement_affect', 0)
    #     Maintain_estimates = request.data.get('Maintain_estimates', 0)
    #     quoted_days = request.data.get('quoted_days', 0)
    #     quoted_hours = request.data.get('quoted_hours', 0)
    #     bugdget_hours = request.data.get('bugdget_hours', 0)
    #     reserve_hours = request.data.get('reserve_hours', 0)
    #     note = request.data.get('note', None)
    #
    #     if project_status != 'O':
    #         raise ValidationError("只有初始状态的项目才可以被更新")
    #
    #     planInstance = ProjectPlanHModel.objects.get(id=projectPlanFK)
    #     quoteInstance = ProjectQuotaModel.objects.get(id=quoteFK)
    #     # 更新维护项目表
    #     maintain_list.projectPlanFK = planInstance
    #     maintain_list.project_name = project_name
    #     maintain_list.project_status = project_status
    #     maintain_list.quoteFK = quoteInstance
    #     maintain_list.order_no = order_no
    #     maintain_list.sales_date = sales_date
    #     maintain_list.sales_amount = sales_amount
    #     maintain_list.procurement_obj = procurement_obj
    #     maintain_list.procurement_affect = procurement_affect
    #     maintain_list.Maintain_estimates = Maintain_estimates
    #     maintain_list.quoted_days = quoted_days
    #     maintain_list.quoted_hours = quoted_hours
    #     maintain_list.bugdget_hours = bugdget_hours
    #     maintain_list.reserve_hours = reserve_hours
    #     maintain_list.note = note
    #
    #     update_instance(maintain_list, request) # 更新五大字段
    #     maintain_list.save()
    #
    #     monthly_sales_amount = round(float(sales_amount) / 12, 2)  # 每个月的“预定销售金额”
    #     monthly_quoted_hours = round(float(quoted_hours) / 12, 2)  # 每个月的“报价工数”
    #     monthly_reserve_hours = round(float(reserve_hours) / 12, 2)  # 每个月的“预算工数”
    #     account_query = ProjectMaintainAccountModel.objects.filter(projectMaintainFK=maintain_id)
    #     for account in account_query:
    #         # 更新项目核算履历表
    #         account.sales_amount = monthly_sales_amount
    #         account.profit_loss = monthly_sales_amount
    #         update_instance(account, request)  # 更新五大字段
    #         account.save()
    #
    #     # 更新阶段别预实管理表
    #     stage_query = ProjectMaintainStageModel.objects.filter(projectMaintainFK=maintain_id)
    #     for stage in stage_query:
    #         stage.quoted_hours = monthly_quoted_hours
    #         stage.bugdget_hours = monthly_reserve_hours
    #         stage.margin_hours = monthly_reserve_hours
    #         update_instance(stage, request)  # 更新五大字段
    #         stage.save()
    #
    #     return maintain_list

    def deleteMaintainProjectRequest(self, maintain_list:ProjectMaintainModel):
        project_id = maintain_list.id
        # 删除项目核算履历信息
        accountQuery = ProjectMaintainAccountModel.objects.filter(projectMaintainFK=maintain_list)
        for data in accountQuery:
            data.delete()

        # 删除阶段别预实管理信息
        stageQuery = ProjectMaintainStageModel.objects.filter(projectMaintainFK=maintain_list)
        for data in stageQuery:
            data.delete()

        # 删除项目进度记录
        query = ProjectProcessModel.objects.filter(projectId=project_id)
        query.delete()

        # 删除维护项目
        maintain_list.delete()

    def updateOrigMaintain(self, old_maintain_id, request):
        old_query               = ProjectMaintainModel.objects.get(id=old_maintain_id)
        old_sales_amount        = old_query.sales_amount
        old_procurement_obj     = old_query.procurement_obj
        old_procurement_affect  = old_query.procurement_affect
        old_Maintain_estimates  = old_query.Maintain_estimates
        old_quoted_days         = old_query.quoted_days
        old_quoted_hours        = old_query.quoted_hours
        old_bugdget_hours       = old_query.bugdget_hours
        old_reserve_hours       = old_query.reserve_hours

        projectPlanFK   = request.get('projectPlanFK')
        plan_status     = projectPlanFK.project_status
        start_date      = projectPlanFK.start_date
        end_date = projectPlanFK.end_date

        sales_date          = request.get('sales_date')
        sales_amount        = request.get('sales_amount')
        procurement_obj     = request.get('procurement_obj')
        procurement_affect  = request.get('procurement_affect')
        Maintain_estimates  = request.get('Maintain_estimates')
        quoted_days         = request.get('quoted_days')
        quoted_hours        = request.get('quoted_hours')
        bugdget_hours       = request.get('bugdget_hours')
        reserve_hours       = request.get('reserve_hours')
        user                = self.request.user
        now                 = datetime.now()
        path                = self.request.path_info
        method              = self.request.method

        # 数据校验
        if plan_status != 'R':
            raise ValidationError("只有生效状态的项目计划书，才能进行项目维护")

        if sales_date < start_date or sales_date > end_date:
            raise ValidationError("预定销售年月必须在项目计划书期间内")

        if sales_amount >= old_sales_amount:
            raise ValidationError("预定销售金额必须小于原始预定销售金额")

        if procurement_obj >= old_procurement_obj:
            raise ValidationError("采购管理对象必须小于原始采购管理对象")

        if procurement_affect > old_procurement_affect:
            raise ValidationError("采购管理事务必须小于等于原始采购管理事务")

        if Maintain_estimates > old_Maintain_estimates:
            raise ValidationError("维护预估金额必须小于等于原始维护预估金额")

        if quoted_days >= old_quoted_days:
            raise ValidationError("报价工数（人日）必须小于原始报价工数（人日）")

        if quoted_hours >= old_quoted_hours:
            raise ValidationError("报价工数（人时）必须小于原始报价工数（人时）")

        if bugdget_hours >= old_bugdget_hours:
            raise ValidationError("预算工数（人时）必须小于原始预算工数（人时）")

        if reserve_hours >= old_reserve_hours:
            raise ValidationError("预算预备工数（人时）必须小于原始预算预备工数（人时）")

        # 插入新拆分后的项目（包括自动将新项目插入到：项目核算履历+阶段别预实管理中）
        new_maintain_list = self.createMaintainProjectRequest(request)

        # 更新原始订单数据
        old_query.sales_amount          = old_sales_amount - sales_amount
        old_query.procurement_obj       = old_procurement_obj - procurement_obj
        old_query.procurement_affect    = old_procurement_affect - procurement_affect
        old_query.Maintain_estimates    = old_Maintain_estimates - Maintain_estimates
        old_query.quoted_days           = old_quoted_days - quoted_days
        old_query.quoted_hours          = old_quoted_hours - quoted_hours
        old_query.bugdget_hours         = old_bugdget_hours - bugdget_hours
        old_query.reserve_hours         = old_reserve_hours - reserve_hours
        old_query.updated               = user
        old_query.updated_date          = now
        old_query.updated_program       = method + ' -> ' + path
        old_query.save()

        monthly_sales_amount    = round(sales_amount / 12, 2)  # 每个月的“预定销售金额”
        monthly_quoted_hours    = round(quoted_hours / 12, 2)  # 每个月的“报价工数”
        monthly_reserve_hours   = round(reserve_hours / 12, 2)  # 每个月的“预算工数”
        # 更新项目核算履历表
        account_query = ProjectMaintainAccountModel.objects.filter(projectMaintainFK=old_maintain_id)
        for account in account_query:
            account_sales_amount    = account.sales_amount # 原始的项目核算履历的营业额
            account_amount          = account.amount # 原始的项目核算履历的耗费
            account.sales_amount    = account_sales_amount - monthly_sales_amount # 更新项目核算履历表的营业额
            account.profit_loss     = account_sales_amount - monthly_sales_amount - account_amount # 更新项目核算履历表的损益
            account.updated         = user
            account.updated_date    = now
            account.updated_program = method + ' -> ' + path
            account.save()

        # 更新阶段别预实管理表
        stage_query = ProjectMaintainStageModel.objects.filter(projectMaintainFK=old_maintain_id)
        for stage in stage_query:
            stage_quoted_hours  = stage.quoted_hours # 原始的报价工数
            stage_bugdget_hours = stage.bugdget_hours # 原始的预算工数
            stage_actual_hours  = stage.actual_hours # 原始的阶段别实绩工数

            stage.quoted_hours  = stage_quoted_hours - monthly_quoted_hours
            stage.bugdget_hours = stage_bugdget_hours - monthly_reserve_hours
            stage.margin_hours  = stage_bugdget_hours - monthly_reserve_hours - stage_actual_hours
            stage.updated       = user
            stage.updated_date  = now
            stage.updated_program = method + ' -> ' + path
            stage.save()
        return new_maintain_list
